-------------------模块区-------------------
serpent = require("serpent")
local mapping = require("mapping")
local dx_json = require("dx_json")
local dx_map = require("dx_map")
local dx_logger = require("dx_logger")

-------------------变量区-------------------
system = "linux"
-- 不持久化的字段，一直取默认值
local un_save = {
	-- 系统版本号
	"sysVersion",
	-- 应用版本号
	"appVersion",
	-- 应用发布日期
	"createTime",
	-- mqtt连接状态
	"mqtt_con_status",
	-- 网络状态
	"network_status"
}
--lua脚本中的全局变量在c语言中也是全局的吗
_G.vbar_config_t = {}

-------------------函数区-------------------
--字符串分割函数
function Split(szFullString, szSeparator)
	local nFindStartIndex = 1
	local nSplitIndex = 1
	local nSplitArray = {}
	while true do
		local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)
		if not nFindLastIndex then
			nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString))
			break
		end
		nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)
		nFindStartIndex = nFindLastIndex + string.len(szSeparator)
		nSplitIndex = nSplitIndex + 1
	end
	return nSplitArray
end

--表的或运算
function merge(tDest, tSrc)
	for k, v in pairs(tSrc) do
		-- if k == "systemtime" then
		--     settime(tSrc["systemtime"])
		-- else
		tDest[k] = v
		-- end
	end
end

--表写入文件
function write_table_to_file(config_table, file_path)
	if type(config_table) ~= "table" then
		print("config_table is not a table")
		return -1
	end
	local file = io.open(file_path, "w+")
	if (file) then
		file:write(serpent.line(config_table))
		file:close()
		os.execute("sync")
		return 0
	end
	return -1
end

function read_table_from_file(file_path)
	local file = io.open(file_path, "r")
	local data
	if file then
		data = file:read("*a")
		file:close()
		if data then
			local ok, config_table_rem = serpent.load(data)
			if type(config_table_rem) == "table" then
				return config_table_rem
			end
		end
	end
	return nil
end

--写入配置表
function writecfg_to_file(filter)
	local ret = write_table_to_file(filter, "/vgapp/etc/config.txt")
	write_table_to_file(filter, "/vgapp/etc/config_bak.txt")
	return ret
end

function writecfg()
	local filter = {}
	if type(vbar_config_t) == "table" then
		for i, v in pairs(vbar_config_t) do
			local flag = true
			for i1, v1 in ipairs(un_save) do
				-- 如果存在不需要持久化的值就跳过
				if v1 == i then
					flag = false
				end
			end
			if flag then
				filter[i] = v
			end
		end
		local ret = writecfg_to_file(filter)
		return ret
	end
	print("in lua writecfg_to_file is not a table")
	return -1
end

--读取配置
function readcfg()
	local table_tmp
	table_tmp = read_table_from_file("/vgapp/etc/config.txt")
	if table_tmp == nil or type(table_tmp) ~= "table" then
		table_tmp = read_table_from_file("/vgapp/etc/config_bak.txt")
	end

	if table_tmp ~= nil and type(table_tmp) == "table" then
		_G.vbar_config_t = table_tmp
		return 0
	end
	return 1
end

--更新配置表
function updatecfg(str)
	-- str == 1.1.0___{wifissid="Vguang_JS", wifipsk="vguangjs_o0"}
	print("updatecfg" .. str)
	assert(str)
	print("updatecfg" .. str)
	local verson, modify, freq = string.match(str, "(%d+).(%d+).(%d+)___")
	if tonumber(verson) ~= 1 then
		return 1
	end
	-- str_t = {wifissid="Vguang_JS", wifipsk="vguangjs_o0"}
	local str_t = Split(str, string.match(str, "%d+.%d+.%d+___"))
	local vbar_config_d
	local ok, is_config_t
	-- 把str_t转换为table
	ok, is_config_t = serpent.load(str_t[2])
	print("str_t[2]: " .. str_t[2])

	if type(is_config_t) == "table" then
		for k, v in pairs(is_config_t) do
			local flag = mapping.isCanBeModify(k)
			if flag == false then
				dx_logger.debug("[updatecfg] 修改配置失败！配置项不能被修改：", k)
				return 1
			end
		end

		vbar_config_d = is_config_t
		if tonumber(modify) > 2 then
			return 1 --版本过高不支持
		end

		-- 合并两个table。vbar_config_d是扫码传入的配置和vbar_config_t原有的配置
		merge(vbar_config_t, vbar_config_d)

		return 0
	else
		return 1
	end
end
--写入配置表
function updatecfg_single(key, val)
	if type(key) == "string" then
		vbar_config_t[key] = val
	end
	return 0
end

--读取配置表
function getvalue(key)
	return vbar_config_t[key]
end

function PrintTable(tbl, level, filteDefault)
	local msg = ""
	filteDefault = filteDefault or true --默认过滤关键字（DeleteMe, _class_type）
	level = level or 1
	local indent_str = ""
	for i = 1, level do
		indent_str = indent_str .. "  "
	end

	print(indent_str .. "{")
	for k, v in pairs(tbl) do
		if filteDefault then
			if k ~= "_class_type" and k ~= "DeleteMe" then
				local item_str = string.format("%s%s = %s", indent_str .. " ", tostring(k), tostring(v))
				print(item_str)
				if type(v) == "table" then
					PrintTable(v, level + 1)
				end
			end
		else
			local item_str = string.format("%s%s = %s", indent_str .. " ", tostring(k), tostring(v))
			print(item_str)
			if type(v) == "table" then
				PrintTable(v, level + 1)
			end
		end
	end
	print(indent_str .. "}")
end
